package com.wang.learn.common.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @source 开源项目pig
 *
 * @author : wcz
 * @version V1.0
 * @Description: spring应用上下文工具类（静态内部类单例）
 */
@Slf4j
@Service
@Lazy(value = false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext=null;

    @Override
    @SneakyThrows
    public void setApplicationContext(ApplicationContext applicationContext){
        SpringContextHolder.applicationContext=applicationContext;
    }

    public static <T> T getBean(String beanName,Class<T> t){
        return applicationContext.getBean(beanName,t);
    }

    public static <T> T getBean(Class<T> t){
        return applicationContext.getBean(t);
    }

    /**
     * 响应事件
     *
     * @param event
     */
    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }

    private static void clear(){
        if (log.isDebugEnabled()){
            log.debug("clear SpringContextHolder.applicationConText ");
        }
        applicationContext=null;
    }

    @Override
    @SneakyThrows
    public void destroy(){
        SpringContextHolder.clear();
    }


}
